package com.tjetc.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.constant.CodeConstant;
import com.tjetc.util.JwtUtils;
import com.tjetc.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author zc
 * @Date 2024/11/8 下午5:22
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("登录校验,拦截token:" + token);
        if (token != null && JwtUtils.checkToken(token)) {
            return true;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(new Result().setCode(CodeConstant.NOT_LOGIN).setMsg("登录信息已过期"));
        response.getWriter().write(json);
        return false;
    }
}
